<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\card;


use app\common\model\card\Card;
use app\common\logic\BaseLogic;
use app\common\model\card\CardOperationLog;
use app\common\model\user\User;
use payment\AirwallexService;
use payment\SlashService;
use payment\WorldFirstService;
use think\facade\Db;


/**
 * card逻辑
 * Class CardLogic
 * @package app\adminapi\logic\card
 */
class CardLogic extends BaseLogic
{


    /**
     * @notes 添加card
     * @param array $params
     * @return bool
     * @author gzx
     * @date 2025/04/11 13:48
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            $data['update_time'] = time();

            //处理卡号和id关系
            if (isset($params['card_no']) && !isset($params['id'])) {
                $cardNos = explode("\n", $params['card_no']);
                foreach ($cardNos as &$cardNo) {
                    $cardNo = trim($cardNo);
                }
                $cardInfos = Card::whereIn('card_no', $cardNos)->select()->toArray();
            } else {
                $cardInfos = Card::whereIn('id', $params['id'])->select()->toArray();
            }

            $num = count($cardInfos);

            if ($num == 0) {
                self::setError('请选择卡片');
                return false;
            }

            foreach ($cardInfos as $k => $cardInfo) {
                if (empty($cardInfo)) {
                    self::setError('卡片不存在');
                    return false;
                }

                if (isset($params['status'])) {
                    if ($params['status'] == 1) {
                        //激活卡片
                        $data['status'] = 1;
                        if ($cardInfo['card_bin'] == 10 || $cardInfo['card_bin'] == 13) {
                            $wordFirstType = match($cardInfo['card_bin']) {
                                10 => 'worldfirst',
                                13 => 'worldfirst_hk',
                            };
                            $worldFirst = new WorldFirstService($wordFirstType);
                            $worldFirst->updateCardStatus($cardInfo['card_id'], 'UNFREEZE');
                        }
                        //空中云付
                        if ($cardInfo['card_bin'] == 11) {
                            $airwallex = new AirwallexService();
                            $airwallex->updateCardStatus($cardInfo['card_id'], 'ACTIVE');
                        }
                        //slash:active, paused, inactive, closed
                        if ($cardInfo['card_bin'] == 12 || $cardInfo['card_bin'] == 15) {
                            $slash = new SlashService($cardInfo['card_bin']);
                            $slash->setCardStatus($cardInfo['card_id'], 'active');
                        }
                    } else {
                        //冻结卡片
                        $data['status'] = 0;
                        if ($cardInfo['card_bin'] == 10 || $cardInfo['card_bin'] == 13) {
                            $wordFirstType = match($cardInfo['card_bin']) {
                                10 => 'worldfirst',
                                13 => 'worldfirst_hk',
                            };
                            $worldFirst = new WorldFirstService($wordFirstType);
                            $worldFirst->updateCardStatus($cardInfo['card_id'], 'FREEZE');
                        }
                        //空中云付
                        if ($cardInfo['card_bin'] == 11) {
                            $airwallex = new AirwallexService();
                            $airwallex->updateCardStatus($cardInfo['card_id'], 'INACTIVE');
                        }
                        //slash
                        if ($cardInfo['card_bin'] == 12 || $cardInfo['card_bin'] == 15 ) {
                            $slash = new SlashService($cardInfo['card_bin']);
                            $slash->setCardStatus($cardInfo['card_id'], 'paused');
                        }
                    }

                    $limit = 0;
                    //更改单笔限额
                    if (isset($params['single_transaction_limit']) && $params['single_transaction_limit'] >= 0) {
                        $data['single_transaction_limit'] = $params['single_transaction_limit'];
                        $limit++;
                    }
                    if (isset($params['daily_transaction_limit']) && $params['daily_transaction_limit'] >= 0) {
                        $data['daily_transaction_limit'] = $params['daily_transaction_limit'];
                        $limit++;
                    }
                    if (isset($params['monthly_transaction_limit']) && $params['monthly_transaction_limit'] >= 0) {
                        $data['monthly_transaction_limit'] = $params['monthly_transaction_limit'];
                        $limit++;
                    }
                    if (isset($params['total_transaction_limit']) && $params['total_transaction_limit'] >= 0) {
                        $data['total_transaction_limit'] = $params['total_transaction_limit'];
                        $limit++;
                    }

                    //限额处理
                    if ($limit == 4) {
                        //冻结的卡片不能修改限额
                        if ($cardInfo['status'] == 0) {
                            $last4 = substr($cardInfo['card_no'], -4);
                            self::setError("卡片尾号{$last4}冻结,不能修改限额");
                            return false;
                        }
                        //对接万里汇
                        if ($cardInfo['card_bin'] == 10 || $cardInfo['card_bin'] == 13) {

                            //处理限额金额，万里付默认限额最大化，2025-7-15讨论
                            if ($params['total_transaction_limit'] < 1) {
                                $params['total_transaction_limit'] = 200000;
                            }
                            if ($params['single_transaction_limit'] < 1) {
                                $params['single_transaction_limit'] = 50000;
                            }
                            if ($params['daily_transaction_limit'] < 1) {
                                $params['daily_transaction_limit'] = 100000;
                            }
                            if ($params['monthly_transaction_limit'] < 1) {
                                $params['monthly_transaction_limit'] = $params['total_transaction_limit'];
                            }


                            //万里付限额处理
                            $wordFirstType = match($cardInfo['card_bin']) {
                                10 => 'worldfirst',
                                13 => 'worldfirst_hk',
                            };
                            $worldFirst = new WorldFirstService($wordFirstType);
                            $worldFirstResult = $worldFirst->updateCardLimit([
                                'asset_id' => $cardInfo['card_id'],
                                'per_transaction_limit_max' => $params['single_transaction_limit'] * 100,
                                'daily_limit_max' => $params['daily_transaction_limit'] * 100,
                                'monthly_limit_max' => $params['monthly_transaction_limit'] * 100,
                                'per_card_limit_max' => $params['total_transaction_limit'] * 100,
                            ]);

                            //更新万里消费额度
                            $data['limit_money'] = $params['monthly_transaction_limit'];

                        }
                        //对接空中云汇
                        if ($cardInfo['card_bin'] == 11) {
                            $limits = [
                                'card_id' => $cardInfo['card_id'],
                                'transaction_limits' => [
                                    "currency" => "USD",
                                    "limits" => []
                                ],
                            ];
                            if ($params['single_transaction_limit']) {
                                $limits['transaction_limits']['limits'][] = [
                                    "amount" => $params['single_transaction_limit'],
                                    "interval" => "PER_TRANSACTION"
                                ];
                            }
                            if ($params['daily_transaction_limit']) {
                                $limits['transaction_limits']['limits'][] = [
                                    "amount" => $params['daily_transaction_limit'],
                                    "interval" => "DAILY"
                                ];
                            }
                            if ($params['monthly_transaction_limit']) {
                                $limits['transaction_limits']['limits'][] = [
                                    "amount" => $params['monthly_transaction_limit'],
                                    "interval" => "MONTHLY"
                                ];
                            }
                            if ($params['total_transaction_limit']) {
                                $limits['transaction_limits']['limits'][] = [
                                    "amount" => $params['total_transaction_limit'],
                                    "interval" => "ALL_TIME"
                                ];
                            }

                            //空中云汇限额处理
                            $airwallex = new AirwallexService();
                            $airwallexResult = $airwallex->updateCardLimit($limits);
                        }


                        //SLASH card
                        if ($cardInfo['card_bin'] == 12 || $cardInfo['card_bin'] == 15) {
                            //限额处理优先级:总>月>天
                            $limit = 0;
                            $preset = 'daily';
                            $single_transaction_limit = $params['single_transaction_limit'] ?? '0';
                            $daily_transaction_limit = $params['daily_transaction_limit'] ?? '0';
                            $monthly_transaction_limit = $params['monthly_transaction_limit'] ?? '0';
                            $total_transaction_limit = $params['total_transaction_limit'] ?? '0';
                            if ($daily_transaction_limit) {
                                $preset = 'daily';
                                $limit = $daily_transaction_limit;
                            }
                            if ($monthly_transaction_limit) {
                                $preset = 'monthly';
                                $limit = $monthly_transaction_limit;
                            }
                            if ($total_transaction_limit) {
                                $preset = 'collective';
                                $limit = $total_transaction_limit;
                            }
                            if ($limit) {
                                //注意，这里是美分，所以*100
                                $slashService = new SlashService($cardInfo['card_bin']);
                                $slashService->setCardRule($cardInfo['card_id'], $preset, $limit * 100, $single_transaction_limit * 100);
                            }
                        }

                    }
                }

                Card::update($data, ['id' => $cardInfo['id']]);
                $request = $params;
                unset($request['admin_info']);
                CardOperationLog::insert([
                    'admin_id' => $params['admin_info']['admin_id'],
                    'card_id' => $cardInfo['card_id'],
                    'card_no' => $cardInfo['card_no'],
                    'params' => json_encode($request),
                    'ip_address' => $_SERVER['REMOTE_ADDR'],
                ]);
            }
            Db::commit();

            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑card
     * @param array $params
     * @return bool
     * @author gzx
     * @date 2025/04/11 13:48
     */
    public static function cvv(array $params): array
    {
        Db::startTrans();
        try {
            if (isset($params['id'])) {
                $where['id'] = $params['id'];
            } elseif (isset($params['card_id'])) {
                $where['card_id'] = $params['card_id'];
            } elseif (isset($params['card_no'])) {
                $where['card_no'] = $params['card_no'];
            } else {
                return [];
            }

            $secureMsg = Card::where($where)->value('secure_msg');

            $msg = decrypt($secureMsg);
            $msg = json_decode($msg, true);

            return $msg;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return [];
        }
    }


    /**
     * @notes 删除card
     * @param array $params
     * @return bool
     * @author gzx
     * @date 2025/04/11 13:48
     */
    public static function delete(array $params): bool
    {
        return Card::destroy($params['id']);
    }

    public static function update(array $params): bool
    {
        Db::startTrans();
        try {

            Card::where('id', $params['id'])->update([
                'status' => $params['status']
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 获取card详情
     * @param $params
     * @return array
     * @author gzx
     * @date 2025/04/11 13:48
     */
    public static function detail($params): array
    {
        return Card::findOrEmpty($params['id'])->toArray();
    }

    public static function import(array $params): bool
    {
        Db::startTrans();
        try {
            // 以 card_id 作为唯一键，有则更新，无则插入
            $card = Card::where('card_id', $params['card_id'])->find();
            if ($card) {
                // 更新
                $card->save([
                    'card_no' => $params['card_no'],
                    'card_bin' => $params['card_bin'],
                    'alias' => $params['alias'],
                    'secure_msg' => $params['secure_msg'],
                    'status' => $params['status'],
                    'remark' => $params['remark'],
                ]);
            } else {
                // 插入
                $in = Card::create([
                    'card_id' => $params['card_id'],
                    'card_no' => $params['card_no'],
                    'card_bin' => $params['card_bin'],
                    'alias' => $params['alias'],
                    'secure_msg' => $params['secure_msg'],
                    'status' => $params['status'],
                    'remark' => $params['remark'],
                ]);
            }

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }
}